<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- table -->
    <!-- 现场人员信息记录 - 首次 -->
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel1" :list="formList" :cols="3" :formType="'add'" labelWidth="140" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <div style="margin-bottom: 1rem;"></div>
    <BreakSpace label="故障信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table1"
      :columns="columns"
      :params="fetchParams"
      :isPagination = false
      :dataSource="dataList"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      selectionType="single"
      height="auto"
      :isSelectColumn=false
      :isColumnFilter="false"
    >
    </FilterTable>
    <div style="margin-bottom: 1rem;"></div>
    <FormPanel ref="formPanel3" :list="formList3" :cols="3" :formType="'add'" labelWidth="140" :isSubmitBtn="false"/>
    <div style="margin-bottom: 2rem;"></div>
    <BreakSpace label="经销商-车厂沟通历史" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table2"
      :columns="columns2"
      :params="fetchParams"
      :isPagination = false
      :dataSource="dataList2"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns2 = columns2)"
      :onRowSelectChange="selectChange"
      selectionType="single"
      height="auto"
      :isSelectColumn=false
    ></FilterTable>
    <div style="margin-bottom: 2rem;"></div>
    <BreakSpace label="质量部回复历史" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table3"
      :columns="columns3"
      :params="fetchParams"
      :isPagination = false
      :dataSource="dataList3"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns3 = columns3)"
      :onRowSelectChange="selectChange"
      selectionType="single"
      height="auto"
      :isSelectColumn=false
    ></FilterTable>
    <div style="margin-bottom: 1rem;"></div>
    <BreakSpace label="现场人员处理过程" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table4"
      :columns="columns4"
      :params="fetchParams"
      :dataSource="dataList4"
      :datakey="'items'"
      :isPagination = false
      :onColumnsChange="columns => (this.columns4 = columns4)"
      :onRowSelectChange="selectChange"
      selectionType="single"
      height="auto"
      :isSelectColumn=false
    >
    </FilterTable>
    <div style="margin-bottom: 1rem;"></div>
    <FormPanel ref="formPanel4" :list="formList4" :cols="3" :formType="'add'" labelWidth="140" :isSubmitBtn="false"/>
    <div style="margin-bottom: 2rem;"></div>
    <BreakSpace label="现场人员处理结果维护" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel2" :list="formList2" :cols="3" :formType="'add'" labelWidth="140" :isSubmitBtn="false" @formChange="formChangeHandle2" />
    <div style="margin-bottom: 1rem;"></div>
    <div style="padding-top: 3rem;"></div>
    <div
      :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" :click="saveDialog.bind()">提 交</multiuse-button>
      <multiuse-button @click="closeDialog">关 闭</multiuse-button>
    </div>
    <BaseDialog :title="'查看附件'" :visible.sync="upVisible" destroyOnClose>
      <uploadFile :rowData="oemId" @close="upVisible = false"></uploadFile>
    </BaseDialog>
  </div>
  </Spin>
</template>
<script>
import uploadFile from '@/pages/claimDemage/TechnicalSupport/uploadFile.vue';
//字典
import { getPartType } from '@/api/dictionary/index';
import { selectById, editSave }  from '@/api/technicalReportManagement/technicalSupportManagement_OEM/onSitePersonnelRecords/index';
import moment from "moment";

export default {
  props: ['rowData'],
  // mixins: [dictionary],
  components: {
    uploadFile
  },
  data() {
    return {
      dataList: [],
      dataList2: [],
      dataList3: [],
      dataList4: [],
      collapse: false,
      loading: false,
      visible: false,
      upVisible: false,
      columns: this.creatHeader(),
      columns2: this.creatHeader2(),
      columns3: this.creatHeader3(),
      columns4: this.creatHeader4(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      formList2: this.createFormList2(),
      formList3: this.createFormList3(),
      formList4: this.createFormList4(),
      saveData: null,
      saveData2: null,
      modelId: null,
      modelCode: null,
      editData: null,
      oemId: null
    };
  },
  async created() {
    this.loading = true;
    await this.chuqi();
    await this.init();
    this.formList2.find(item => item.fieldName === 'estDate').minDateTime=this.getAllocatedTime();
    this.loading = false;
  },
  methods: {
    async init() {
      const newVar = await selectById({id: this.rowData.techId});
      this.editData = newVar.data;
      this.modelId = newVar.data.modelId;
      this.modelCode = newVar.data.modelCode;
      console.log("=== 通过ID查询结果返回 ==== ",this.editData," ======");
      this.formList.forEach(x => {
        console.log(newVar);
        x.initialValue = newVar.data[x.fieldName];
      });
      this.formList2.forEach(x => {
        x.initialValue = newVar.data[x.fieldName];
        // if (x.fieldName == 'applyFileList') {
        //   x.initialValue = newVar.data.applyFileList.map((f) => ({ name: f.title, url: f.fileUrl }));
        // }
      });
      this.formList3.forEach(x => {
        if (x.fieldName == 'applyFileList') {
          x.initialValue = newVar.data.applyFileList.map((f) => ({ name: f.title, url: f.fileUrl }));
        }
      });
      this.formList4.forEach(x => {
        if (x.fieldName == 'dealFileList') {
          x.initialValue = newVar.data.dealFileList.map((f) => ({ name: f.title, url: f.fileUrl }));
        }
      });
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(newVar.data.faultList);
      this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(newVar.data.oemList);
      this.$refs.table3.$refs.pageTable.EXECUTE_INSERT(newVar.data.qualityList);
      this.$refs.table4.$refs.pageTable.EXECUTE_INSERT(newVar.data.siteList);


      this.loading = false;
    },
    async chuqi() {
      //是否首次咨询
      const res1 = await getPartType({type: 5500});
      if (res1.resultCode == 200) {
        this.formList.find(x => x.fieldName == 'ifFirst').itemList = res1.data.map(y => ({
          text: y.codeCnDesc,
          value: y.codeId
        }));
      }
      //状态
      const res2 = await getPartType({type: 5552});
      if (res2.resultCode == 200) {
        this.formList.find(x => x.fieldName == 'techStatus').itemList = res2.data.map(y => ({
          text: y.codeCnDesc,
          value: y.codeId
        }));
      }
      //受理类型
      const res3 = await getPartType({type: 5553});
      if (res3.resultCode == 200) {
        this.formList.find(x => x.fieldName == 'acceptType').itemList = res3.data.map(y => ({
          text: y.codeCnDesc,
          value: y.codeId
        }));
      }
      // //处理方式
      // const res4 = await getPartType({type: 5554});
      // if (res4.resultCode == 200) {
      //   this.formList.find(x => x.fieldName == 'dealType').itemList = res4.data.map(y => ({
      //     text: y.codeCnDesc,
      //     value: y.codeId
      //   }));
      // }
    },
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },
    formChangeHandle2(val) {
      console.log(val);
      this.saveData2 = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
      console.log(val);
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //保存
    async saveDialog() {
      this.$refs.formPanel1.SUBMIT_FORM();
      this.$refs.formPanel2.SUBMIT_FORM();

      console.log('newSave', this.saveData)
      console.log('newSave2', this.saveData2)

      //单据状态 技术报告草稿，提交 字典码
      let save = {};
      save = Object.assign({}, this.saveData, this.saveData2);

      //techId主表主键
      save.techId = this.editData.techId;
      //系统ID
      save.appId = this.editData.appId;
      //所有者代码
      save.ownerCode = this.editData.ownerCode;
      //所有者的父组织代码
      save.ownerParCode = this.editData.ownerParCode;
      //组织ID
      save.orgId = this.editData.orgId;
      //是否删除
      save.isDeleted = this.editData.isDeleted;
      //创建人ID
      save.createdBy = this.editData.createdBy;
      //创建时间
      save.createdAt = this.editData.createdAt;
      //版本号
      save.recordVersion = this.editData.recordVersion;
      //经销商ID
      save.dealerId = this.editData.dealerId;
      //车型ID
      save.modelId = this.modelId;
      //车型代码
      save.modelCode = this.modelCode;
      //首次提交时间
      save.firstDate = this.editData.firstDate;
      //处理方式
      save.dealType = this.editData.dealType;
      //销售日期
      save.saleDate = this.editData.saleDate;
      //生产日期
      save.prodDate = this.editData.prodDate;
      //维修方案
      save.cmsClaimCase = this.editData.cmsClaimCase;
      //故障现象描述
      save.faultInfo = this.editData.faultInfo;
      //检修经过
      save.cmsClaimProcess = this.editData.cmsClaimProcess;
      //维修结果
      save.cmsClaimResult = this.editData.cmsClaimResult;
      //接单人
      save.takerName = this.editData.takerName;
      //申请日期
      save.applyDate = this.editData.applyDate;
      //联系电话
      save.sitePhone = this.editData.sitePhone;
      //邮箱
      save.siteEmail = this.editData.siteEmail;
      //评价结果
      save.evaluateResult = this.editData.evaluateResult;
      //评价人
      save.evaluateBy = this.editData.evaluateBy;
      //评价时间
      save.evaluateAt = this.editData.evaluateAt;
      //评价描述
      save.evaluateRemarks = this.editData.evaluateRemarks;
      //现场评价结果
      save.siteEvaluateResult = this.editData.siteEvaluateResult;
      //现场评价人
      save.siteEvaluateBy = this.editData.siteEvaluateBy;
      //现场评价时间
      save.siteEvaluateAt = this.editData.siteEvaluateAt;
      //现场评价描述
      save.siteEvaluateRemarks = this.editData.siteEvaluateRemarks;
      //现场处理人
      save.siteDealer = this.editData.siteDealer;
      //技术支持报告审核状态
      save.auditStatus = this.editData.auditStatus;
      //维修工单
      save.roNo = this.editData.roNo;
      //经销端是否已解决
      save.dlrIfDeal = this.editData.dlrIfDeal;

      if (this.saveData2.AaAa === 1) {
        save.techStatus = 55521004; //已分配
      } else {
        save.techStatus = 55521003; //已提交
        save.refuse = 1;
        // save.dealType = null;
        save.siteDealer = null;
        save.sitePhone = null;
        save.siteEmail = null;
        save.disDate = null;
      }
      // console.log(this.editData.dealType);
      console.log(save);
      this.loading = true;

      this.$confirm('请确认是否处理完成，提交后不能再次修改！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await editSave(save);
          if (res.resultCode === 200) {
            this.$emit('save');
            return this.$notify.success({title: '提示信息', message: '提交成功'});
          } else {
            this.loading = false;
          }
        })

    },
    //取消操作
    closeDialog() {
      this.$emit('close', {visible: false, data: this.selectedRows, type: 'close'});
    },
    fileOemTurnOn(val) {
      this.oemId = val.oemId;
      this.upVisible = true;
    },
    getAllocatedTime()
    {
      let res=this.formList2.find(item => item.fieldName === 'disDate').initialValue;
     return res;
    },
    fileQaTurnOn(val) {
      this.oemId = val.qaId;
      this.upVisible = true;
    },
    //基本信息
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '技术报告单号',
          fieldName: 'techNo',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'techStatus',
          itemList: [],
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'SELECT',
          label: '是否首次咨询',
          fieldName: 'ifFirst',
          itemList: [],
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择经销商代码',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: '所属区域',
          fieldName: 'belongArea',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: '经销商联系人',
          fieldName: 'dcPerson',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: '经销商联系人电话',
          fieldName: 'dcTel',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'DATE',
          label: '提交时间',
          fieldName: 'firstDate',
          dateType: 'datetime',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请选择VIN',
          readonly: true,// 只读
          disabled: true// 置会
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelName',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: '行驶里程',
          fieldName: 'driveMile',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'DATE',
          label: '生产日期',
          fieldName: 'prodDate',
          valueFormat: 'yyyy-MM-dd',
          dateType: 'datetime',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'DATE',
          label: '销售日期',
          fieldName: 'saleDate',
          valueFormat: 'yyyy-MM-dd',
          dateType: 'datetime',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'licenseNo',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'SELECT',
          label: '故障类型',
          fieldName: 'acceptType',
          placeholder: '受理类型',
          itemList: [],
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'TEXT_AREA',
          label: '说明',
          fieldName: 'techInfos',
          selfCols: 3,
          rows: 2,
          readonly: true,// 只读
          disabled: true // 置会
        },
      ];
    },
    //故障信息
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {title: '一级', dataIndex: 'sysName1', sorter: true},
        {title: '二级', dataIndex: 'sysName2', sorter: true},
        {title: '三级', dataIndex: 'sysName3', sorter: true},
        {title: '故障名称', dataIndex: 'sysName4', sorter: true},
        {title: '故障现象代码', dataIndex: 'faultCode', sorter: true},
        {title: '故障现象名称', dataIndex: 'faultName', sorter: true},
        {title: '故障Id', dataIndex: 'faId', sorter: true, hidden: true},
        {title: '故障码', dataIndex: 'errorCode', sorter: true},
        {title: '故障码触发条件', dataIndex: 'faultCondition', sorter: true},
        {title: '本车是否首发', dataIndex: 'ifFirst', sorter: true, hidden: true},
        {title: '本车是否首发', dataIndex: 'ifFirstStr', sorter: true},
        {title: '备注', dataIndex: 'remarks', sorter: true}
      ];
    },
    //故障信息附件
    createFormList3() {
      return [
        {
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'applyFileList',
          placeholder: '上传文件...',
          initialValue: [],
          readonly: true,// 只读
          disabled: true, // 置会
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 2,
            // tipText: '只能上传pdf格式'
          }
        }
      ];
    },
    //经销商-车厂沟通历史
    creatHeader2() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: (props, h) => {
            return (
              <div>
                <multiuse-button  size="mini" type="text" onClick={() => this.fileOemTurnOn(props.row)}>
                  查看附件
                </multiuse-button>
              </div>
            );
          }
        },
        { title: '经销商人员', dataIndex: 'dealerUser', sorter: true },
        { title: '经销商提交时间', dataIndex: 'dApplyDate', sorter: true },
        { title: '故障现象描述', dataIndex: 'faultInfo', sorter: true },
        { title: '检修经过', dataIndex: 'cmsClaimProcess', sorter: true },
        { title: '维修结果', dataIndex: 'cmsClaimResult', sorter: true },
        { title: '车厂处理人', dataIndex: 'dealBy', sorter: true },
        { title: '车厂处理时间', dataIndex: 'dealDate', sorter: true },
        { title: '维修方案', dataIndex: 'cmsClaimCase', sorter: true },
        // { title: '附件', dataIndex: 'date1', sorter: true },
      ];
    },
    //质量部回复历史
    creatHeader3() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: (props, h) => {
            return (
              <div>
                <multiuse-button  size="mini" type="text" onClick={() => this.fileQaTurnOn(props.row)}>
                  查看附件
                </multiuse-button>
              </div>
            );
          }
        },
        {title: '联系人', dataIndex: 'connectBy', sorter: true},
        {title: '联系电话', dataIndex: 'connectPhone', sorter: true},
        {title: '回复状态', dataIndex: 'connectStatus', sorter: true},
        {title: '反馈时间', dataIndex: 'connectDate', sorter: true},
        {title: '处理意见', dataIndex: 'cmsClaimCase', sorter: true},
        {title: '附件', dataIndex: 'date', sorter: true}
      ];
    },
    //现场人员处理过程
    creatHeader4() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // { title: '现场处理人', dataIndex: 'siteDealerStr', sorter: true },
        { title: '日期', dataIndex: 'siteDate', sorter: true },
        { title: '进度', dataIndex: 'speedPro', sorter: true },
        { title: '维修经过', dataIndex: 'cmsClaimProcess', sorter: true }
      ];
    },
    //现场人员处理过程附件
    createFormList4() {
      return [
        {
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'dealFileList',
          placeholder: '上传文件...',
          initialValue: [],
          readonly: true,// 只读
          disabled: true, // 置会
          upload: {
            actionUrl: '/api/file/oss/upload',
            //limit: 2,
            // tipText: '只能上传pdf格式'
          }
        }
      ];
    },
    //现场人员处理结果维护
    createFormList2() {
      return [
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'AaAa',
          itemList: [{text: '接受', value: 1}, {text: '拒绝', value: 0}],
          rules: [{ required: true, message: '请选择单据状态', trigger: 'change' }],
          change: val => {
            if (val == 1) {
              this.formList2.map(y => {
                if (y.fieldName == 'estDate') {
                  y.disabled = false;
                  y.rules = [{required: true, message: '请选择预计到达时间', trigger: 'change'}];
                }
              })
            } else {
              this.formList2.map(y => {
                if (y.fieldName == 'estDate') {
                  y.disabled = true;
                  y.initialValue = '';
                  y.rules = [{required: false, message: '', trigger: 'change'}];
                }
              })
            }
          }
        },
        {
          type: 'INPUT',
          label: '现场处理人',
          fieldName: 'siteDealerStr',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'DATE',
          label: '分配时间',
          fieldName: 'disDate',
          placeholder: '分配时间',
          valueFormat: 'yyyy-MM-dd',
          dateType: 'datetime',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'DATE',
          label: '预计到达时间',
          fieldName: 'estDate',
          placeholder: '分配时间',
          valueFormat: 'yyyy-MM-dd',
          dateType: 'datetime',
          minDateTime:null,
          disabled: true, // 置会
          rules: [{ required: false, message: '请选择预计到达时间', trigger: 'change' }]
        },
        // {
        //   type: 'TEXT_AREA',
        //   label: '备注',
        //   fieldName: 'remark',
        //   placeholder: '请输入',
        //   selfCols: 3
        // },
      ];
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .el-form-item {
  white-space:normal !important;
}
</style>
